﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using ESF.General.Entity;
using ESF.General;

#endregion


namespace ESF.Web.ServerControls
{
	[AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand, 
        Level = AspNetHostingPermissionLevel.Minimal),
	ToolboxData("<{0}:SelectEnterprise runat=\"server\"></{0}:SelectEnterprise>")]
	public class SelectEnterprise : WebControl, INamingContainer
	{
		#region Delegados

		public event Func<BaseEnterprise, bool> VerifyEnterprise;

		#endregion


		#region Miembros

		private Label lblTitle;

		private RequiredFieldValidator rfvtxtEnterprise;

		private TextBox txtEnterprise;

		private HyperLink lnkClear;

		private AjaxControlToolkit.AutoCompleteExtender auctxtEnterprise; 

		#endregion


		#region Properties

		public string OnlyListEnterpriseType
		{
			set
			{
				auctxtEnterprise.ContextKey = value;
			}
		}


		public bool IsRequired
		{
			set
			{
				EnsureChildControls(); 
				
				rfvtxtEnterprise.Enabled = value;
			}
			get
			{
				return rfvtxtEnterprise.Enabled;
			}
		}


		public string ValidationGroup
		{
			set
			{
				EnsureChildControls ();

				rfvtxtEnterprise.ValidationGroup = value;
			}
		}


		public string ReadOnlyEnterpriseTypes
		{
			set
			{
				ViewState["ReadOnlyEnterpriseTypes"] = value;
			}
			get
			{
				return ViewState["ReadOnlyEnterpriseTypes"] as string;
			}
		}


		public int EnterpriseNameMaxLength
		{
			set
			{
				EnsureChildControls ();
				
				txtEnterprise.MaxLength = value;
			}
		}


		public new bool IsEnabled
		{
			set
			{
				EnsureChildControls(); 
				
				txtEnterprise.Enabled = value;
			}
		}


		public string ListEnterprisesServiceMethod
		{
			set
			{
				EnsureChildControls ();

				auctxtEnterprise.ServiceMethod = value;
			}
		}


		public string ListEnterprisesServicePath
		{
			set
			{
				EnsureChildControls();

				auctxtEnterprise.ServicePath = value;
			}
		}


		public string Title
		{
			set
			{
				EnsureChildControls ();

				lblTitle.Text = value;
			}
		}


		public IEnterprise SelectedEnterprise
		{
			get
			{
				BaseEnterprise result;

				string[] partesEntidad = null;


				if (!TextHelper.IsEmpty(txtEnterprise.Text) && txtEnterprise.Text.Contains("|"))
				{
					partesEntidad = txtEnterprise.Text.Split('|');

					if (partesEntidad.Length != 3)
					{
						JS.AddWarning(Page, "Diligencie nuevamente la Entidad y seleccione una de la lista sugerida.\nEn caso de no encontrarlo deje el campo en blanco");
						return null;
					}
				}

				if (partesEntidad == null)
				{
					if (IsRequired)
					{
						throw new GenericInfoException (string.Format ("Diligencie la {0}", lblTitle.Text));
					}
					else
					{
						return null; 
					}
				}

				result = new BaseEnterprise () 
				{ 
					IdentificationNumber = partesEntidad[1], 
					IdentificationType = new BasicReference () { Code = partesEntidad[0] },
					Name = partesEntidad[2] 
				};

				if (VerifyEnterprise == null)
				{
					throw new Exception ("No ha sido definido el manejador de VerifyEnterprise");
				}

				if (!VerifyEnterprise (result))
				{
					JS.AddWarning(Page, "La entidad seleccionada no corresponde a una registrada");
					return null;
				}

				return result;
			}
			set
			{
				if (value == null || value.IdentificationType == null || string.IsNullOrWhiteSpace (value.IdentificationNumber) || string.IsNullOrWhiteSpace (value.Name))
				{
					txtEnterprise.Text = string.Empty;
				}
				else
				{
					txtEnterprise.Text = value.IdentificationType.Code + "|" + value.IdentificationNumber + "|" + value.Name;

					if (value.Type != null)
					{
						txtEnterprise.ReadOnly = TextHelper.IsIn(value.Type.Code, TextHelper.Split('|', ReadOnlyEnterpriseTypes));
					}
				}
			}
		}

		#endregion


		#region Initialize

		protected override void CreateChildControls()
		{
			lblTitle = new Label ();
			lblTitle.Text = "Entidad";

			txtEnterprise = new TextBox ();
			txtEnterprise.ID = "txtEnterprise";

			rfvtxtEnterprise = new RequiredFieldValidator ();
			rfvtxtEnterprise.ID = "rfvtxtEnterprise";
			rfvtxtEnterprise.ControlToValidate = txtEnterprise.ID;
			rfvtxtEnterprise.Display = ValidatorDisplay.Dynamic;
			rfvtxtEnterprise.Enabled = false;
			rfvtxtEnterprise.ErrorMessage = "Diligencie parte del nombre de la Entidad";
			rfvtxtEnterprise.Text = "*";

			auctxtEnterprise = new AjaxControlToolkit.AutoCompleteExtender ();
			auctxtEnterprise.ID = "auctxtEnterprise";
			auctxtEnterprise.UseContextKey = true;
			auctxtEnterprise.EnableCaching = false;
			auctxtEnterprise.ContextKey = string.Empty;
			auctxtEnterprise.TargetControlID = txtEnterprise.ID;
			auctxtEnterprise.MinimumPrefixLength = 3;
			auctxtEnterprise.CompletionInterval = 700;  
			auctxtEnterprise.CompletionSetCount = 20;
			auctxtEnterprise.EnableCaching = false;
						
			lnkClear = new HyperLink ();
			lnkClear.ID = "lnkClear";
			lnkClear.CssClass = "lnkClear";
			lnkClear.Text = "Limpiar";
			lnkClear.NavigateUrl = "#";
			
			Controls.Add(lblTitle); 
			Controls.Add(rfvtxtEnterprise); 
			Controls.Add(txtEnterprise);
			Controls.Add(auctxtEnterprise);
			Controls.Add (lnkClear);
		}

		#endregion


		#region Funciones
		
		public void Clear ()
		{
			txtEnterprise.Text = string.Empty;
		}

		#endregion


		#region Render

		protected override void OnPreRender(EventArgs e)
		{
			lnkClear.Attributes["onclick"] = "$('#" + txtEnterprise.ClientID + "').val ('');";
			
			if (IsRequired && !lblTitle.Text.Contains ("*"))
			{
				lblTitle.Text = lblTitle.Text + " *";
			}
		}


		protected override void Render(HtmlTextWriter pWriter)
		{
				pWriter.AddAttribute (HtmlTextWriterAttribute.Class, "divField");
			pWriter.RenderBeginTag (HtmlTextWriterTag.Div);

					pWriter.AddAttribute (HtmlTextWriterAttribute.Class, "label");
				pWriter.RenderBeginTag(HtmlTextWriterTag.Div);
					lblTitle.RenderControl (pWriter);
					lnkClear.RenderControl (pWriter);					
				pWriter.RenderEndTag();

					pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "field");
				pWriter.RenderBeginTag(HtmlTextWriterTag.Div);
					txtEnterprise.RenderControl (pWriter);
					auctxtEnterprise.RenderControl (pWriter);
					rfvtxtEnterprise.RenderControl (pWriter);

						pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "instructions");
					pWriter.RenderBeginTag(HtmlTextWriterTag.Div);
						pWriter.Write ("Diligencie al menos tres (3) caracteres del nombre, o identificación de la Entidad para luego de un instante observar un listado de sugerencias del cual puede seleccionar uno");
					pWriter.RenderEndTag();

				pWriter.RenderEndTag();

			pWriter.RenderEndTag ();
		}

		#endregion
		
	}
}
